//#define USE_IAP

using System;
using UnityEngine;

#if USE_IAP
using UnityEngine.Purchasing;
#endif

/**
支付成功后得到订单号，如果想通过自己游戏服二次验证订单是否真正支付成功以防止玩家作弊，看以下信息：
( 苹果官方文档：https://developer.apple.com/library/content/releasenotes/General/ValidateAppStoreReceipt/Chapters/ValidateRemotely.html )
正式验证api地址
https://buy.itunes.apple.com/verifyReceipt
沙箱验证api地址
https://sandbox.itunes.apple.com/verifyReceipt
参数：receipt-data
请求方式：POST
 */

namespace BToolkit
{
#if USE_IAP
    public class IAPUnity : IStoreListener
    {

        private static IAPUnity instance;
        public static IAPUnity Instance { get { return instance ?? (instance = new IAPUnity()); } }
        IStoreController m_StoreController;
        IExtensionProvider m_StoreExtensionProvider;
        bool IsInitialized { get { return m_StoreController != null && m_StoreExtensionProvider != null; } }
        Action<bool> InitCallback;
        Action<string> PurchaseCallback;
      
        private IAPUnity() { }

        public void Init(string[] productIDs, Action<bool> InitCallback)
        {
            this.InitCallback = InitCallback;
            if (!IsInitialized)
            {
                Debug.Log("IAP >>>>>>>> 初始化");
                ConfigurationBuilder builder = ConfigurationBuilder.Instance(StandardPurchasingModule.Instance());
                for (int i = 0; i < productIDs.Length; i++)
                {
                    Debug.Log("Add Product:" + productIDs[i]);
                    builder.AddProduct(productIDs[i], ProductType.Consumable);
                }
                UnityPurchasing.Initialize(this, builder);
            }
            else
            {
                Debug.Log("IAP >>>>>>>> 已初始化过了");
                this.InitCallback?.Invoke(true);
            }
        }

        public void Buy(string productId, Action<string> PurchaseCallback)
        {
            Debug.Log("IAP >>>>>>>> Buy: " + productId);
            this.PurchaseCallback = PurchaseCallback;
            if (IsInitialized)
            {
                Product product = m_StoreController.products.WithID(productId);
                if (product != null && product.availableToPurchase)
                {
                    m_StoreController.InitiatePurchase(product);
                    return;
                }
                else
                {
                    Debug.LogError("IAP >>>>>>>> 商品无法购买");
                }
            }
            else
            {
                Debug.LogError("IAP >>>>>>>> IAP未初始化");
                this.PurchaseCallback?.Invoke(null);
            }
        }

        /// <summary>
        /// 当已经支付拿到订单ID,但未收到支付成功的通知时，可以使用该方法继续验证，等同于再购买一次但苹果不会再让用户进行支付
        /// </summary>
        public void Restore(Action<string> RestoreCallback)
        {
            Debug.Log("IAP >>>>>>>> Restore");
            PurchaseCallback = RestoreCallback;
            if (IsInitialized)
            {
                var apple = m_StoreExtensionProvider.GetExtension<IAppleExtensions>();
                Debug.Log("IAP >>>>>>>>  RestoreTransactions");
                apple.RestoreTransactions((success) =>
                {
                    //返回一个bool值，如果成功，则会多次调用支付回调，然后根据支付回调中的参数得到商品id，最后做处理(ProcessPurchase)  
                    Debug.Log("IAP >>>>>>>>  success:" + success);
                    if (!success)
                    {
                        this.PurchaseCallback?.Invoke(null);
                    }
                });
            }
            else
            {
                Debug.LogError("IAP >>>>>>>> 未初始化");
                this.PurchaseCallback?.Invoke(null);
            }
        }

        public void OnInitialized(IStoreController controller, IExtensionProvider extensions)
        {
            Debug.Log("IAP >>>>>>>> 初始化成功");
            m_StoreController = controller;
            m_StoreExtensionProvider = extensions;
            this.InitCallback?.Invoke(true);
        }

        public void OnInitializeFailed(InitializationFailureReason error)
        {
            Debug.LogError("IAP >>>>>>>> 初始化失败:" + error);
            this.InitCallback?.Invoke(false);
        }

        public PurchaseProcessingResult ProcessPurchase(PurchaseEventArgs e)
        {
            Debug.Log("IAP >>>>>>>> 支付成功:" + e.purchasedProduct.definition.id);
            this.PurchaseCallback?.Invoke(e.purchasedProduct.definition.id);
            return PurchaseProcessingResult.Complete;
        }

        public void OnPurchaseFailed(Product product, PurchaseFailureReason p)
        {
            Debug.LogError("IAP >>>>>>>> 支付失败 StoreSpecificId:" + product.definition.storeSpecificId + " PurchaseFailureReason:" + p);
            this.PurchaseCallback?.Invoke(null);
        }

    }
#endif
}
